<!-- 分账方案列表 -->
<template>
  <div>
    <a-modal :width="1200" title="分账方案列表" :open="openForm" @cancel="onClose" :maskClosable="false" :destroyOnClose="true" :footer="false">
      <div>
        <a-form class="smart-query-form">
          <a-row class="smart-query-form-row">
            <a-col :span="6">
              <a-form-item label="分账接收方账户" class="smart-query-form-item">
                <a-input v-model:value="queryForm.receiverAccount" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="分账关系" class="smart-query-form-item">
                <a-select v-model:value="queryForm.relationType" allowClear :options="RELATION_TYPE_ALLOC" placeholder="请选择" />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="getSettlementList">
                  <template #icon>
                    <SearchOutlined />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                  <template #icon>
                    <ReloadOutlined />
                  </template>
                  重置
                </a-button>
              </a-form-item></a-col
            >
          </a-row>
        </a-form>

        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block" v-if="USER_TYPE == '4'">
          <div class="smart-table-title"></div>
          <div class="smart-table-setting-block">
            <a-button type="primary" class="m-r-3" @click="addData"> 添加 </a-button>
          </div>
        </a-row>
        <a-table
          :dataSource="tableData"
          :columns="columns"
          bordered
          childrenColumnName="allocDetails"
          :defaultExpandAllRows="true"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <div class="smart-table-operate">
                <a-button @click="deleteRow(record)" type="link">删除</a-button>
              </div>
            </template>
          </template>
        </a-table>

        <div class="smart-query-table-page">
          <a-pagination
            showSizeChanger
            showQuickJumper
            show-less-items
            :defaultPageSize="queryForm.pageSize"
            v-model:current="queryForm.pageNo"
            v-model:pageSize="queryForm.pageSize"
            :total="total"
            @change="getSettlementList"
            @showSizeChange="getSettlementList"
            :show-total="(total) => `共${total}条`"
          />
        </div>
      </div>

      <a-modal
        title="添加方案"
        :width="1000"
        :open="openRelation"
        @cancel="onRelationModalClose"
        :maskClosable="false"
        :destroyOnClose="true"
        @ok="onRelationSubmit"
      >
        <a-form :model="relationForm" ref="formRef" :rules="rules">
          <a-row class="smart-query-form-row">
            <a-col :span="24">
              <a-form-item label="分账接收方账号" name="receiverId">
                <CustomSelect
                  v-model:value="relationForm.receiverId"
                  :placeholder="'请选择'"
                  :api="allocRelationApiMerchant.page"
                  :queryParams="queryParam"
                  queryParamKey="receiverName"
                  labelField="receiverName"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="分账比例(%)" name="ratio">
                <a-input-number class="w-full" v-model:value="relationForm.ratio" :precision="2" placeholder="请输入" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <template #footer>
          <a-space>
            <a-button @click="onRelationModalClose">取消</a-button>
            <a-button type="primary" @click="onRelationSubmit">保存</a-button>
          </a-space>
        </template>
      </a-modal>
    </a-modal>
  </div>
</template>
<script setup>
  import { nextTick, reactive, ref, computed, watch } from 'vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { allocRuleApi as allocRuleApiMerchant } from '/@/api/business/b-merchant/alloc/alloc-rule.js'
  import { allocRelationApi as allocRelationApiMerchant } from '/@/api/business/b-merchant/alloc/alloc-relation.js'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import dayjs from 'dayjs'
  import _ from 'lodash'
  import {
    USER_TYPE_ALLOC, //用户类型
    ALLOC_DETAIL_STATUS, //'分账明细-分账状态'
    RECEICER_TYPE, //接收方账户类型
    BIND_STATUS_ALLOC, //绑定状态
    RELATION_TYPE_ALLOC, //分账关系
  } from '/@/constants/dict'
  import { selectDictLabel, formatToMoney } from '/@/utils/common'
  import { message, Modal } from 'ant-design-vue'

  import { useUserStore } from '/@/store/modules/system/user'
  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户

  const apiSource = {
    listApi: (data) => {
      if (USER_TYPE == '4') return allocRuleApiMerchant.page(data)
    },
    delete: (data) => {
      if (USER_TYPE == '4') return allocRuleApiMerchant.delete(data)
    },
    insert: (data) => {
      if (USER_TYPE == '4') return allocRuleApiMerchant.insert(data)
    },
  }

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emit = defineEmits(['update:open', 'ok', 'cancel'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  const queryFormState = {
    // cTime: [dayjs().startOf('day'), dayjs().endOf('day')], //交易时间
    // cTimeBegin: dayjs().startOf('day').valueOf(), //交易时间 开始
    // cTimeEnd: dayjs().endOf('day').valueOf(), //交易时间 结束
    receiverAccount: undefined,
    relationType: undefined,
    pageNo: 1,
    pageSize: 10,
  }
  // 查询表单form
  const queryForm = ref({ ...queryFormState })
  async function getSettlementList(data) {
    tableLoading.value = true
    try {
      const payload = { ...queryForm.value, productId: props.rowData?.id }
      delete payload.tTime
      let queryResult = await apiSource.listApi(payload)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      console.log(e)
    } finally {
      tableLoading.value = false
    }
  }
  async function show(rowData) {
    console.log(rowData)

    await getSettlementList()
    // nextTick(() => {
    //   formRef.value?.clearValidate()
    // })
  }

  function onClose() {
    tableData.value = []
    // Object.assign(form, formDefault)
    emit('cancel', false)
    openForm.value = false
  }

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.value.pageSize
    Object.assign(queryForm.value, queryFormState)
    queryForm.value.pageSize = pageSize
    getSettlementList()
  }
  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)
  // ------------------------ 表单 ------------------------

  /* 列表数据 */

  const columns = ref([
    {
      title: '序号',
      dataIndex: 'index',
      customRender: ({ index }) => {
        return (queryForm.value.pageNo - 1) * queryForm.value.pageSize + index + 1
      },
    },
    {
      title: '分账接收方账号',
      dataIndex: 'receiverAccount',
      ellipsis: true,
    },
    {
      title: '分账关系',
      dataIndex: 'relationType',
      customRender: ({ text }) => {
        return selectDictLabel(RELATION_TYPE_ALLOC, text)
      },
      ellipsis: true,
    },
    {
      title: '姓名',
      dataIndex: 'receiverName',
      ellipsis: true,
    },
    {
      title: '联系方式',
      dataIndex: 'receiverPhone',
      ellipsis: true,
    },
    {
      title: '分账比例(%)',
      dataIndex: 'ratio',
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'cTime',
      customRender: (column) => (column.text ? dayjs(column.text).format('YYYY-MM-DD HH:mm:ss') : ''),
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
    },
  ])
  // 时间选择
  function onChangeTTime(dates) {
    queryForm.value.cTimeBegin = dates[0].valueOf()
    queryForm.value.cTimeEnd = dates[1].valueOf()
  }
  // 删除
  function deleteRow(row) {
    Modal.confirm({
      title: '删除',
      content: '确定要删除吗?',
      okText: '删除',
      okType: 'danger',
      async onOk() {
        SmartLoading.show()
        try {
          await apiSource.delete({ id: row.id })
          message.success('删除成功')
          await getSettlementList()
        } catch (error) {
          console.log(error)
        } finally {
          SmartLoading.hide()
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  /* 新增关系 */
  const openRelation = ref(false)
  const infoForm = {
    receiverId: undefined, //分账关系(0:服务商;1:门店;2:员工;3:店主;4:合作伙伴;5:总部;6:品牌方;7:分销商;8:用户;9:供应商;10:自定义)
    ratio: undefined,
    channelId: undefined,
    productId: undefined,
  }
  const relationForm = ref({ ...infoForm })
  const rules = {
    receiverId: [{ required: true, message: '分账接收方账号 必填', trigger: ['change', 'blur'] }],
    ratio: [{ required: true, message: '分账比例 必填', trigger: ['change', 'blur'] }],
  }
  const formRef = ref()
  const addData = () => {
    openRelation.value = true
  }
  const onRelationModalClose = () => {
    nextTick(() => {
      formRef.value?.clearValidate()
    })
    relationForm.value = infoForm
    openRelation.value = false
  }
  const onRelationSubmit = () => {
    relationForm.value.channelId = props.rowData?.channelId
    relationForm.value.productId = props.rowData?.id
    formRef.value.validate().then(() => {
      apiSource.insert(relationForm.value).then((e) => {
        if (e.code === 200) {
          message.success('新增成功')
          onRelationModalClose()
          resetQuery()
        }
      })
    })
  }
  /* 新增关系 */

  const queryParam = computed(() => {
    return {
      channelId: props.rowData?.channelId,
      status: 1,
    }
  })

  /* 列表数据 */

  defineExpose({
    show,
  })
  // 切换订单号选择
  watch(
    () => queryForm.value.orderField,
    (val, oldVal) => {
      if (val) {
        queryForm.value[oldVal] = undefined
      }
    },
  )
  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
